import { getCustomColumn } from "@/api/common";
import { baseUrlApi } from "@/api/utils";
import { addDialog } from "@/components/ReDialog";
import FilePreview from "@/components/common/FilePreview";
import { useUserStoreHook } from "@/store/modules/user";
import BigNumber from "bignumber.js";
import dayjs from "dayjs";
import { ElMessageBox, ElTag } from "element-plus";
import { h } from "vue";
import { getToken } from "./auth";
import { message } from "./message";

// 数字转中文
export function numberToChinese(num) {
  if (isNaN(num) || num > 99999) return "超出范围";
  const digits = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
  const units = [
    "",
    "十",
    "百",
    "千",
    "万",
    "十",
    "百",
    "千",
    "亿",
    "十",
    "百",
    "千"
  ];

  let result = "";
  let strNum = num.toString();
  for (let i = 0; i < strNum.length; i++) {
    const digit = parseInt(strNum[i]);
    const unit = units[strNum.length - 1 - i];
    if (digit === 0) {
      // 处理连续的零（如 1001 → 一千零一）
      if (result[result.length - 1] !== "零") {
        result += digits[digit];
      }
    } else {
      result += digits[digit] + unit;
    }
  }
  // 处理结尾的零（如 100 → 一百）
  return result.replace(/零+$/, "").replace(/零万/, "万") || "零";
}

export const getTableCol = async moduleKey => {
  let tableCol = {
    key: moduleKey,
    load: true,
    size: "default",
    col: []
  };
  let { data } = await getCustomColumn(moduleKey);
  if (data?.columnJson) {
    let colData = JSON.parse(data.columnJson);
    tableCol.size = colData.size;
    tableCol.col = colData.col;
  }
  return tableCol;
};

export const exportData = (exportName, api, queryParams) => {
  ElMessageBox.confirm(`是否确认导出 '${exportName}' 数据?`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    dangerouslyUseHTMLString: true,
    draggable: true
  }).then(async () => {
    let url = baseUrlApi(api);
    let params = "";
    Object.keys(queryParams).forEach(key => {
      if (queryParams[key] || queryParams[key] === 0) {
        params += `${params ? "&" : "?"}${key}=${queryParams[key]}`;
      }
    });
    let finalUrl = url + params;
    handleDownload({
      exportName: `${exportName}_${dayjs().format("YYYY-MM-DD")}.xls`,
      exportUrl: finalUrl
    });
  });
};

// 下载文件
function handleDownload(exportData) {
  changeBlob(exportData.exportUrl).then(res => {
    saveAs(res, exportData.exportName);
  });
}

function changeBlob(url) {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.setRequestHeader("accessToken", getToken()?.accessToken);
    xhr.responseType = "blob";
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };
    xhr.send();
  });
}

function saveAs(blob, exportName) {
  let newBlob = new Blob([blob], {
    // type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    type: "application/vnd.ms-excel"
  });
  var link = document.createElement("a");
  link.href = window.URL.createObjectURL(newBlob);
  link.download = exportName;
  link.click();
  message("导出成功", { type: "success" });
}

export const isCanPreview = (formData, dataId) => {
  let falg = false;
  const userId = useUserStoreHook().id;
  const userType = useUserStoreHook().userType;
  if (dataId || userType == 2 || userId == formData?.createUserId) {
    falg = true;
  }
  return falg;
};

export const numberFormat = number => {
  if (!number) {
    return "--";
  }
  number = number + "";

  const re = /^(-?\d+)(\d{3})(\.?\d*)/;
  while (re.test(number)) {
    number = number.replace(re, "$1,$2$3");
  }

  return number;
};

/**
 * treeData 分为上下级
 * @param treeData 原数据
 * @param parentIdKey
 * @param parentNamekey
 * @param itemNameKey
 * @returns
 */
export function dealTreeList(
  treeData: Array<any>,
  parentIdKey: string,
  parentNamekey: string,
  itemNameKey: string
) {
  let tempList = [];
  treeData.forEach(item => {
    let obj = tempList.find(v => v.id == item[parentIdKey]);
    if (obj) {
      obj.children.push({
        id: item.id,
        label: item[itemNameKey] || "--"
      });
    } else {
      tempList.push({
        id: item[parentIdKey],
        label: item[parentNamekey] || "--",
        children: [
          {
            id: item.id,
            label: item[itemNameKey] || "--"
          }
        ]
      });
    }
  });
  return tempList;
}

// 数据 * 100
export function dealDataRide(data, flag = 100, decimal = undefined) {
  if (!data) {
    return "";
  } else {
    data = new BigNumber(data);
    return decimal
      ? data.times(flag).toFormat(decimal)
      : data.times(flag).toNumber();
  }
}

// 数据 / 100
export function dealDataExcept(data, flag = 100, decimal = undefined) {
  if (!data) {
    return "";
  } else {
    data = new BigNumber(data);
    return decimal
      ? data.div(flag).toFormat(decimal)
      : data.div(flag).toNumber();
  }
}

// 处理相加
export function dealDataAdd(data, flag = 0) {
  if (!data) {
    return "";
  } else {
    data = new BigNumber(data);
    return data.plus(flag || 0).toNumber();
  }
}

// 处理相减
export function dealDataCut(data, flag = 0) {
  if (!data) {
    return "";
  } else {
    data = new BigNumber(data);
    return data.minus(flag || 0).toNumber();
  }
}

// 日期格式化
export function formatDate(date, defaultStr = "--", flag = "YYYY-MM-DD") {
  if (!date) {
    return defaultStr;
  }
  return dayjs(date).format(flag);
}

// 日期格式化
export function formatDate_hm(date, flag = "YYYY-MM-DD HH:mm") {
  if (!date) {
    return "--";
  }
  return dayjs(date).format(flag);
}

export function tableFilePreview(row, fileKey) {
  const userId = useUserStoreHook().id;
  const userType = useUserStoreHook().userType;
  if (userType == 2 || userId == row?.createUserId) {
    openFilePreview(row[fileKey]);
  } else {
    message("文件不可预览", { type: "warning" });
  }
}

export function openFilePreview(fileData, fileIndex = 0) {
  if (!fileData) {
    return message("预览文件为空", { type: "warning" });
  }
  addDialog({
    title: "文件预览",
    props: {
      fileData: fileData || [],
      fileIndex: fileIndex || 0
    },
    width: "1000px",
    draggable: true,
    overflow: true,
    fullscreenIcon: true,
    contentRenderer: () => h(FilePreview),
    beforeSure: done => {
      done();
    }
  });
}

// 审核状态 0 审核中 1 已审核 2 已驳回
export const examineStatusStr = status => {
  if (status == null) {
    return "--";
  }
  let statusMap = {
    0: { text: "审核中", type: "warning" },
    1: { text: "已审核", type: "warning" },
    2: { text: "已驳回", type: "success" }
  };
  let obj = statusMap[status];
  if (!obj) {
    return "--";
  }
  console.log("111", obj);
  return h(ElTag);
};

let commonUtil = {
  dealDataRide, // 数据乘 默认10 *10
  dealDataExcept, // 数据除 默认10 /10
  dealDataAdd, // 数据相加
  dealDataCut // 数据相减
};

export default commonUtil;
